<template>
  <div class="admin-page">
    <div class="page-header">
      <h2>存储管理</h2>
    </div>

    <div class="admin-content">
      <!-- 存储统计 -->
      <div class="storage-stats">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon">
                  <el-icon><Folder /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ storageStats.totalSizeFormatted }}</div>
                  <div class="stat-label">总存储空间</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ storageStats.usedSizeFormatted }}</div>
                  <div class="stat-label">已使用空间</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon">
                  <el-icon><Files /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ storageStats.fileCount }}</div>
                  <div class="stat-label">文件总数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon">
                  <el-icon><FolderOpened /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-value">{{ storageStats.folderCount }}</div>
                  <div class="stat-label">文件夹总数</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 使用率图表 -->
      <div class="usage-chart">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>存储使用率</span>
              <div>
                <el-button type="text" @click="syncStorage" :loading="loading">
                  <el-icon><Refresh /></el-icon> 同步数据
                </el-button>
                <el-button type="text" @click="refreshStats">刷新</el-button>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <el-progress
              type="circle"
              :percentage="storageStats.usagePercentage"
              :width="120"
              :stroke-width="8"
            >
              <template #default="{ percentage }">
                <span class="percentage-value">{{ percentage }}%</span>
              </template>
            </el-progress>
          </div>
        </el-card>
      </div>

      <!-- 用户存储统计 -->
      <div class="user-storage">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户存储统计</span>
              <el-button type="primary" @click="handleCleanup">清理过期文件</el-button>
            </div>
          </template>
          <el-table :data="userStorageList" v-loading="loading" v-if="userStorageList.length > 0">
            <el-table-column label="用户昵称" prop="userName" />
            <el-table-column label="总空间" prop="totalSizeFormatted" />
            <el-table-column label="已使用" prop="usedSizeFormatted" />
            <el-table-column label="使用率" width="120">
              <template #default="{ row }">
                <el-progress
                  :percentage="row.usagePercentage || 0"
                  :stroke-width="6"
                  :show-text="false"
                />
                <span class="progress-text">{{ row.usagePercentage || 0 }}%</span>
              </template>
            </el-table-column>
            <el-table-column label="文件数" prop="fileCount" />
            <el-table-column label="文件夹数" prop="folderCount" />
            <el-table-column label="最后清理" prop="lastCleanupTime" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="handleSetQuota(row)"
                  :disabled="row.totalSize === 0"
                >
                  设置配额
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  @click="handleInitStorage(row)"
                  v-if="row.totalSize === 0"
                >
                  初始化
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无数据" />
        </el-card>
      </div>
    </div>

    <!-- 设置存储配额对话框 -->
    <el-dialog
      v-model="quotaDialogVisible"
      title="设置存储配额"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="quotaForm" label-width="100px">
        <el-form-item label="用户昵称">
          <el-input v-model="quotaForm.userName" disabled />
        </el-form-item>
        <el-form-item label="存储配额" required>
          <el-input-number
            v-model="quotaForm.totalSizeGB"
            :min="0.1"
            :max="1000"
            :precision="1"
            :step="0.1"
            placeholder="请输入存储配额（GB）"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="说明">
          <el-text type="info" size="small">
            设置用户可使用的最大存储空间，单位：GB
          </el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="quotaDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmQuota" :loading="quotaLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Folder, Document, Files, FolderOpened, Refresh } from '@element-plus/icons-vue'
import type { CdUserStorageVo } from '@/types/cd'
import { storageApi } from '@/api/cd'

const loading = ref(false)
const userStorageList = ref<CdUserStorageVo[]>([])

// 配额设置对话框
const quotaDialogVisible = ref(false)
const quotaLoading = ref(false)
const quotaForm = reactive({
  userId: 0,
  userName: '',
  totalSizeGB: 1
})

const storageStats = reactive({
  totalSize: 0,
  usedSize: 0,
  fileCount: 0,
  folderCount: 0,
  totalSizeFormatted: '0 B',
  usedSizeFormatted: '0 B',
  usagePercentage: 0
})

onMounted(() => {
  loadUserStorageList()
})

const loadUserStorageList = async () => {
  loading.value = true
  try {
    console.log('开始加载用户存储统计...')
    const response = await storageApi.getAllUserStorage()
    console.log('存储统计API响应:', response)
    
    if (response.data) {
      const data = response.data
      console.log('存储统计数据:', data)
      
      // 从 stats 中获取总计数据
      const stats = data.stats
      const users = data.users || []
      
      // 更新存储统计（总计）
      storageStats.totalSize = stats.totalSize || 0
      storageStats.usedSize = stats.usedSize || 0
      storageStats.fileCount = stats.fileCount || 0
      storageStats.folderCount = stats.folderCount || 0
      storageStats.totalSizeFormatted = formatSize(stats.totalSize || 0)
      storageStats.usedSizeFormatted = formatSize(stats.usedSize || 0)
      storageStats.usagePercentage = stats.totalSize > 0 
        ? Math.round((stats.usedSize / stats.totalSize) * 100) 
        : 0
      
      // 更新用户存储列表，为每个用户计算格式化的数据
      userStorageList.value = users.map(user => ({
        ...user,
        totalSizeFormatted: formatSize(user.totalSize || 0),
        usedSizeFormatted: formatSize(user.usedSize || 0),
        usagePercentage: user.totalSize > 0 
          ? Math.round((user.usedSize / user.totalSize) * 100) 
          : 0,
        lastCleanupTime: user.lastCleanupTime || '-'
      }))
      
      console.log('更新后的存储统计:', storageStats)
      console.log('用户存储列表:', userStorageList.value)
    }
  } catch (error) {
    console.error('加载用户存储统计失败:', error)
    ElMessage.error('加载用户存储统计失败')
  } finally {
    loading.value = false
  }
}

const syncStorage = async () => {
  loading.value = true
  try {
    // 先同步当前用户的存储统计
    await storageApi.syncStorage()
    ElMessage.success('存储统计同步成功')
    // 重新加载所有用户的存储统计
    await loadUserStorageList()
  } catch (error) {
    console.error('同步存储统计失败:', error)
    ElMessage.error('同步存储统计失败')
  } finally {
    loading.value = false
  }
}

const refreshStats = () => {
  loadUserStorageList()
  ElMessage.success('统计数据已刷新')
}

const formatSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleCleanup = async () => {
  try {
    // TODO: 实现清理过期文件
    ElMessage.success('清理完成')
  } catch (error) {
    console.error('清理失败:', error)
    ElMessage.error('清理失败')
  }
}

// 设置存储配额
const handleSetQuota = (row: any) => {
  quotaForm.userId = row.userId
  quotaForm.userName = row.userName
  quotaForm.totalSizeGB = row.totalSize ? (row.totalSize / (1024 * 1024 * 1024)) : 1
  quotaDialogVisible.value = true
}

// 初始化用户存储
const handleInitStorage = async (row: any) => {
  try {
    await storageApi.initUserStorage(row.userId)
    ElMessage.success('用户存储统计初始化成功')
    await loadUserStorageList()
  } catch (error) {
    console.error('初始化用户存储失败:', error)
    ElMessage.error('初始化用户存储失败')
  }
}

// 确认设置配额
const handleConfirmQuota = async () => {
  if (!quotaForm.totalSizeGB || quotaForm.totalSizeGB <= 0) {
    ElMessage.warning('请输入有效的存储配额')
    return
  }

  quotaLoading.value = true
  try {
    const totalSizeBytes = Math.round(quotaForm.totalSizeGB * 1024 * 1024 * 1024)
    await storageApi.setUserStorageQuota(quotaForm.userId, totalSizeBytes)
    ElMessage.success('存储配额设置成功')
    quotaDialogVisible.value = false
    await loadUserStorageList()
  } catch (error) {
    console.error('设置存储配额失败:', error)
    ElMessage.error('设置存储配额失败')
  } finally {
    quotaLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.admin-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
  
  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }
}

.admin-content {
  .storage-stats {
    margin-bottom: 24px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          font-size: 32px;
          color: #409eff;
          margin-right: 16px;
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .usage-chart {
    margin-bottom: 24px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      
      .percentage-value {
        font-size: 18px;
        font-weight: 500;
        color: #409eff;
      }
    }
  }
  
  .user-storage {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .progress-text {
      margin-left: 8px;
      font-size: 12px;
      color: #606266;
    }
  }
}
</style>
